package com.daka.auth;

import com.daka.tools.CookieUtil;
import com.daka.tools.SessionHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jayli
 *         <p>
 *         限制请求连接只能访问指定的接口 暂时不用
 */
@Service
public class WeixinInterceptor extends HandlerInterceptorAdapter {
    protected Logger LOGGER = LoggerFactory.getLogger(WeixinInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURL().toString();
        String paramString = request.getQueryString();
        LOGGER.info("/WeixinInterceptor/preHandle, requestUrl" + " ,wechat-ngo : " + requestUrl + "?" + paramString);

        String cookieOpenId = CookieUtil.getCookieOpenid(request);
        LOGGER.info("/WeixinInterceptor/preHandle, cookie in openId" + cookieOpenId);
        if (cookieOpenId != null) {
            LOGGER.info("/WeixinInterceptor/preHandle, spUrl.getRedirectUrl  paramString " + paramString);

            //从cookie中取出openId放入SessionHold    如果cookie中有openId默认相信cookie中的
            SessionHolder.setOpenId(cookieOpenId);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        SessionHolder.clearSessionHolder();
    }
}
